<template>
  <view>
    <view class="custom_top">
      <view class="item left">
        <i class="back iconfont icon-xiangzuo2" @click="goBack"></i>
        <i class="home iconfont icon-shouye" @click="goHome"></i>
      </view>
      <view class="item title">{{conversation.name}}</view>
      <view class="item right"></view>
    </view>
    <view class="custom_top_blank"></view>
    <view class="chat">
      <scroll-view
        class="scrollview"
        id="scrollview"
        scroll-y="true"
        :scroll-top="scrollTop"
        @scroll="onscroll"
        :style="{ height: scrollview + 'rpx' }"
      >
        <view class="chatbody" id="chatbody" v-if="!data_list_loading">
          <view class="chat_items" v-if="data_list.length > 0">
            <view v-for="(item, index) in data_list" :key="index">
              <view class="item" :class=" item.ident == 1 ? 'item_left' : 'item_right' ">
                <view class="item_bd">
                  <image class="avatar" :src="item.avatar" mode="scaleToFill" />
                  <view class="chat_content">
                    <view class="txtbox">{{item.message}}</view>
                    <view class="send_status" v-if="item.send_status && item.send_status == 1">发送中</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="empty_msg" v-if="data_list.length == 0">
            暂无最新消息
          </view>
        </view>
      </scroll-view>

      <view class="chat_foot_blank"></view>
      <view class="chat_foot">
        <view class="bd">
          <view class="inputbox">
            <input
              class="weui-input"
              type="txt"
              placeholder="请输入"
              @input="setmessage"
              @confirm="sendMessage"
              v-model="message"
            />
          </view>
          <view class="vm2" @click="sendMessage">发送</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from "@/utils/http.js"
export default {
  data() {
    return {
      loading: true,
      data_list: [],
      data_list_loading: true,
      loadmore_status: 'loadmore',
      loadmore_finished: false,
      params: {
        page_size: 15,
        page: 1,
      },
      loginUser: {},
      conversation: {},

      scrollTop: 0, // 目前没用到
      scrollview: 0,
      message: '',

      timer: null,
      lastMessageId: 0,
    }
  },

  onLoad: function(options) {
    let that = this;
    uni.getSystemInfo({
      success: function (res) {
        let windowHeight = that.rpxTopx(res.windowHeight);
        // 浏览器高度 - 自定义头部高度 - 底部高度
        // 转换rpx
        that.scrollview = windowHeight - that.rpxTopx(66) - that.rpxTopx(54);
      }
    })

    this.id = options.id;
    uni.showLoading();
    request.post('/im/getConversation', { id: this.id }).then(res => {
      this.loading = false;
      uni.hideLoading();
      if (res.data === null) {
        uni.showModal({
          content: '会话不存在',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              uni.navigateBack();
            }
          }
        });
      }
      this.conversation = res.data;
    })

    this.getInit();

    request.post('/user/getLoginUser').then(res => {
      this.loginUser = res.data;
    })

    setInterval(this.fetchNewMessages, 9000);
  },

  methods: {
    fetchNewMessages: function() {
      if (this.data_list_loading) return false;
      let params = { id: this.id, lastMessageId: this.lastMessageId };
      request.post('/im/fetchNewMessages', params).then(res => {
        if (res.code == 200 && res.data.length > 0) {
          this.lastMessageId = res.data[res.data.length - 1].id;
          res.data.forEach((item, index) => {
            let obj = {
              id: item.id,
              ident: item.ident,
              avatar: item.avatar,
              message: item.message,
            };
            this.data_list.push(obj);
          })
          this.scrollToBottom();
        }
      })
    },

    // px转换成rpx
    rpxTopx(px){
      let deviceWidth = wx.getSystemInfoSync().windowWidth;
      let rpx = ( 750 / deviceWidth ) * Number(px);
      return Math.floor(rpx)
    },

    // 滑动到顶部加载 加载更多信息
    onscroll: function(e) {
      if (e.detail.scrollTop == 0) {
        this.getMore();
      }
    },

    // 滚动至聊天底部
    scrollToBottom(e) {
      setTimeout(() => {
        let query = uni.createSelectorQuery().in(this);
        query.select('#scrollview').boundingClientRect();
        query.select('#chatbody').boundingClientRect();
        query.exec((res) => {
          if (res[1].height > res[0].height) {
            this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
          }
        })
      }, 15)
    },

    // 消息内容
    setmessage: function(e) {
      this.message = e.target.value;
    },

    // 发送消息
    sendMessage: function() {
      if (this.message != '' && !/^\s+$/.test(this.message)) {
        let message = this.message;
        let currentDate = new Date();
        let timestamp = currentDate.getTime();
        let obj = {
          id: timestamp,
          ident: 0,
          avatar: this.loginUser.avatar,
          message: message,
          send_status: 1,
        };
        this.data_list.push(obj);
        this.message = '';
        this.scrollToBottom();

        let params = { id: this.id, message: message };
        request.post('/im/sendMessage', params).then(res => {
          if (res.code == 200) {
            this.lastMessageId = res.data;
            let data_list = this.data_list;
            for (var i = 0; i < data_list.length; i++) {
              if (data_list[i].id == timestamp) {
                data_list[i].send_status = 0;
                data_list[i].id = res.data;
              }
            }
            this.data_list = data_list;
          } else if (res.code == 400) {
            uni.showToast({ title: res.message, icon: 'none' });
          }
        })
      }
    },

    // 请求接口，获取列表数据
    getConversationMessages: function() {
      let params = this.params;
      params.id = this.id;
      request.post('/im/getConversationMessages', params).then(res => {
        uni.stopPullDownRefresh();
        uni.hideLoading();
        this.data_list_loading = false;

        // 返回数据为空
        if (res.data.total == 0) {
          this.data_list = [];
          return false;
        }

        // 组装数据
        if (res.data.current_page == 1) {
          this.data_list = res.data.data;
          this.scrollToBottom();
          this.lastMessageId = res.data.data[res.data.data.length - 1].id;
        } else {
          this.data_list = res.data.data.concat(this.data_list);
        }

        // 最后一页
        if (this.params.page == res.data.last_page) {
          this.loadmore_finished = true;
          this.loadmore_status = 'nomore';
          return false;
        }

        this.params.page = parseInt(res.data.current_page) + parseInt(1);
        this.loadmore_status = 'loadmore';
        this.loadmore_finished = false;
      })
    },

    // 初始化请求
    getInit: function() {
      uni.showLoading()
      this.params.page = 1;
      this.getConversationMessages();
    },

    // 加载更多
    getMore: function() {
      if (!this.loadmore_finished) {
        //uni.showLoading();
        this.loadmore_status = 'loading';
        this.getConversationMessages();
      }
    },

    goBack: function() {
      uni.navigateBack();
    },

    goHome: function() {
      uni.switchTab({ url: '/pages/index/index' });
    },

    switchTab: function(url) {
      uni.switchTab({ url: url });
    },

    jumpPage: function(url) {
      uni.navigateTo({ url: url });
    }
  }
}
</script>

<style>
@import url("im.css");
page {

}
.custom_top_blank {
  height: 54px;
  padding-top: var(--status-bar-height);
}
.custom_top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 99;
  height: 53px;
  line-height: 53px;
  border-bottom: 1px solid #f9f9f9;
  background: #fff;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: var(--status-bar-height);
}
.custom_top .item {
  flex: 1;
}
.custom_top .left .iconfont {
  font-weight: 600;
  font-size: 18px;
}
.custom_top .left .iconfont:not(:first-child) {
  margin-left: 12px;
}
.custom_top .title {
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow:ellipsis;
}
.custom_top .right {
  text-align: right;
  color: #999;
  font-size: 14px;
}
.custom_top .right .iconfont {}
</style>
